package cn.bluemobi.dylan.step.presenter.main;

import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import cn.bluemobi.dylan.step.base.RxPresenter;
import cn.bluemobi.dylan.step.moder.bean.User;
import cn.bluemobi.dylan.step.moder.http.CommonSubscriber;
import cn.bluemobi.dylan.step.moder.http.RetrofitHelper;
import cn.bluemobi.dylan.step.moder.http.RxUtil;
import cn.bluemobi.dylan.step.moder.http.response.HttpResponseBean;
import cn.bluemobi.dylan.step.moder.prefs.Prefs;
import cn.bluemobi.dylan.step.moder.prefs.SharedPreferencesHelper;
import cn.bluemobi.dylan.step.presenter.contract.main.MainContract;
import cn.bluemobi.dylan.step.moder.bean.StepData;
import cn.bluemobi.dylan.step.step.utils.DbUtils;
import cn.bluemobi.dylan.step.utils.common.DateUtil;
import cn.bluemobi.dylan.step.utils.common.LogUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * Created by $Liudan on 2018/8/7 0007.
 */
public class MainPresenter extends RxPresenter<MainContract.View> implements MainContract.Presenter {
    @Inject
    SharedPreferencesHelper prefHelper;

    @Inject
    public MainPresenter() {

    }

    /**
     * 获取user
     */
    public void preUser() {
        Observable<User> observable = Observable.create(new ObservableOnSubscribe<User>() {
            @Override
            public void subscribe(ObservableEmitter<User> emitter) throws Exception {
                User user = prefHelper.getPrefObject(Prefs.key_user, User.class);
                emitter.onNext(user);
                emitter.onComplete();
            }
        });
        //创建一个下游 Observer
        Observer<User> observer = new Observer<User>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(User user) {
                if (user != null) {
                    mView.prefUserSuccess(user);
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
        //建立连接
        observable.subscribe(observer);

    }

    /**
     * 获取当天步数 本地数据库获取
     */
    public void dbTodayStepcount(){

        Observable<List<StepData>> observable = Observable.create(new ObservableOnSubscribe<List<StepData>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StepData>> emitter) throws Exception {
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String sdfDate =  sdf.format(date); //当前日期
                long CURRENT_DATE =DateUtil.dateToStampDay(sdfDate);
                //获取当天的数据，用于展示
                List<StepData> list = DbUtils.getQueryByWhere(StepData.class, "stepTime", new Long[]{CURRENT_DATE});

                emitter.onNext(list);
                emitter.onComplete();
            }
        });
        //创建一个下游 Observer
        Observer<List<StepData>> observer = new Observer<List<StepData>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(List<StepData> list) {
                if (list != null && list.size() > 0) {
                    mView.showStepcount(list.get(0));
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
        //建立连接
        observable.subscribe(observer);

    }

    /**
     * 今日步数  服务器获取 ,完成后开启计步service
     */
    public void todayStep(int memberId){
        addSubscribe(RetrofitHelper.getStepcountApi().todayStep(memberId)
                .compose(RxUtil.<HttpResponseBean<StepData>>rxSchedulerHelper())
                .compose(RxUtil.<StepData>handleResult())
                .subscribeWith(new CommonSubscriber<StepData>(mView) {
                    @Override
                    public void onNext(StepData user) {
                        mView.httpStepCountSuccess(user);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mView.startStepService();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mView.startStepService();
                    }
                })
        );
    }




    /**
     * 上传未上传的历史步数
     */
    public void dbUplodStepcountList(){


        Observable<List<StepData>> observable = Observable.create(new ObservableOnSubscribe<List<StepData>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StepData>> emitter) throws Exception {
                List<StepData> list = DbUtils.getQueryAll(StepData.class);
                emitter.onNext(list);
                emitter.onComplete();
            }
        });
        //创建一个下游 Observer
        Observer<List<StepData>> observer = new Observer<List<StepData>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(List<StepData> list) {
                if (list != null && list.size() > 0) {
                    updateMemberStepForDayList(list);
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
        //建立连接
        observable.subscribe(observer);

    }

    /**
     * 上传
     */
    public void updateMemberStepForDayList(final List<StepData> list){

        String json = new Gson().toJson(list);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);

        addSubscribe(RetrofitHelper.getStepcountApi().updateMemberStepForDayList(body)
                .compose(RxUtil.<HttpResponseBean<User>>rxSchedulerHelper())
                .compose(RxUtil.<User>handleResult())
                .subscribeWith(new CommonSubscriber<User>(mView) {
                    @Override
                    public void onNext(User user) {
//                        mView.httpSuccess();
                        LogUtils.debug(this.getClass().getName(),"11111111111111111上传计步数据成功"+list.size());
                        dbUplodStepcountListStatus(list);
                    }
                })
        );
    }


    /**
     * 上传成功后修改状态
     */
    public void dbUplodStepcountListStatus(final List<StepData> list){
        for(int i=0;i<list.size();i++){
            list.get(i).setStatus(1);
        }

        Observable<List<StepData>> observable = Observable.create(new ObservableOnSubscribe<List<StepData>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StepData>> emitter) throws Exception {
                DbUtils.updateALL(list);
                emitter.onNext(list);
                emitter.onComplete();
            }
        });
        //创建一个下游 Observer
        Observer<List<StepData>> observer = new Observer<List<StepData>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(List<StepData> list) {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
        //建立连接
        observable.subscribe(observer);

    }


    /**
     * 保存今日步数
     *
     * 如果服务器比本地步数大 需要保存更新本地今日步数
     */
    public void dbSaveTodyStepCount(final StepData stepData){

        Observable<List<StepData>> observable = Observable.create(new ObservableOnSubscribe<List<StepData>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StepData>> emitter) throws Exception {

                //获取当天的数据，用于展示
                List<StepData> list = DbUtils.getQueryByWhere(StepData.class, "stepTime", new Long[]{stepData.getStepTime()});
                if (list != null && list.size() > 0) { //本地数据库有,更新
                    DbUtils.update(stepData);
                }else {
                    DbUtils.insert(stepData);
                }
                emitter.onNext(list);
                emitter.onComplete();
            }
        });
        //创建一个下游 Observer
        Observer<List<StepData>> observer = new Observer<List<StepData>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(List<StepData> list) {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
        //建立连接
        observable.subscribe(observer);


    }


}
